//
//  HNEffect.m
//  HeroNuts
//
//  Created by Vicky on 6/7/11.
//  Copyright 2011 Tongji University. All rights reserved.
//

#import "HNEffect.h"
#import "HNEffectCache.h"
#import "GameScene.h"
#import "HNLogicPosition.h"
#import "HNAudioEngine.h"

@implementation HNEffect

@synthesize effectName = effectName_;

- (id)initWithEffectName:(NSString *)effect
{
    if ((self = [super init])) 
	{
        self.effectName = effect;
        
        actions_ = [[NSMutableArray alloc] init];
        
        NSString *effectSpriteFrameName = [[HNEffectCache sharedEffectCache] firstFrameNameOfEffect:effect];
        effectSprite_ = [[CCSprite alloc] initWithSpriteFrameName:effectSpriteFrameName];
        [[[GameScene sharedGameScene] effectLayer] addChild:effectSprite_];
        
        CCAnimate *animate = [[HNEffectCache sharedEffectCache] effectByName:effect];
        CCCallFunc *playEffect = [CCCallFunc actionWithTarget:self selector:@selector(playSoundEffect)];
        
        CCSpawn *animateWithSound = [CCSpawn actionOne:animate two:playEffect];
        [actions_ addObject:animateWithSound];
    }
    
    return self;
}

- (void)playSoundEffect
{
    [[HNAudioEngine sharedEngine] playSoundEffect:effectName_];
}

- (void)startWithTarget:(HNActor*)aTarget
{
    target_ = aTarget;
    
    CGPoint distance = [HNLogicPosition distanceInPixelsFrom:ccp(0,0) to:target_.position];
    CGPoint originalPosition = [[HNEffectCache sharedEffectCache] originalPositionOfEffect:effectName_];
    effectSprite_.position = ccpAdd(distance, originalPosition);
    effectSprite_.anchorPoint = ccp(0,1);
    
    CCCallFunc *endEffect = [CCCallFunc actionWithTarget:self selector:@selector(onEffectFinished)];
    
    CCSequence *sequence = [CCSequence actionOne:[actions_ objectAtIndex:0] two:endEffect];
    
    [effectSprite_ runAction:sequence];
}

- (void)onEffectFinished
{
    [effectSprite_ removeFromParentAndCleanup:YES];
    [self notifyCompletion];
}

- (void)dealloc
{
    [effectName_ release];
    [effectSprite_ release];
    [super dealloc];
}


@end
